import { defineStore } from 'pinia'
import axios from 'axios'

interface LoginState {
  userId: number | null
  isAuthenticated: boolean
}

export const useLoginStore = defineStore('login', {
  state: (): LoginState => ({
    userId: null,
    isAuthenticated: false
  }),
  actions: {
    async fetchUserId() {
      try {
        // 直接调用验证接口，依赖HttpOnly的JSESSIONID
        const res = await axios.get('/api/user/verify')
        this.userId = res.data.data.id
        this.isAuthenticated = true
      } catch (error) {
        this.clearAuth()
        throw error
      }
    },
    clearAuth() {
      this.userId = null
      this.isAuthenticated = false
    }
  },
  getters: {
    isAuthenticated: (state) => state.isAuthenticated
  }
})
